<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :class="{disable:fileList.length>0}"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="progressShow" :percentage="percentage" status="success" style="width:148px" :show-text="false" />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 引入腾讯云文档并且实例化
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID64tWv9Bya2MTN3TuCKPL3XnpcFsMflcI',
  SecretKey: 'bx41lGWAcrrcFtSpy1ua4NUP6ZnmW4Ra'
})
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      // 进度条
      progressShow: false,
      percentage: 0
    }
  },
  mounted() {
    // 钩子函数
  },
  methods: {
    // 删除文件的钩子
    handleRemove(file, fileList) {
      this.fileList = [...fileList]
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件状态改变时的钩子
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('只支持jpeg/png格式')
        return false
      }
      const maxSize = 500 * 1024
      if (file.size > maxSize) {
        this.$message.error('大小不能超过 500 kb')
        return false
      }
    },
    // 覆盖默认的上传行为，可以自定义上传的实现
    upload(params) {
      this.progressShow = true
      cos.putObject({
        Bucket: 'hr63-1306481095', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          this.percentage = (progressData.percent) * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
          // console.log(this.fileList)
        }
        setTimeout(() => {
          this.progressShow = false
        }, 500)
      })
    }
  }
}
</script>

<style lang="scss">
img {
  object-fit: cover;
}

.disable {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
